package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 消息的发送者
 */
@RestController
@RequestMapping("/mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 消息发送
     */
    //http://localhost:8282/mq/sendDeadLettle
    @GetMapping("sendConfirm")
    public Result sendConfirm() {
        // 消息的主体 以时间作为消息的内容
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        rabbitService.sendMessage("exchange.confirm", "routing.confirm788", sdf.format(new Date()));

        return Result.ok();
    }

    /**
     * 发送消息 - 基于死信实现延迟消息
     * http://localhost:8282/mq/sendDeadLettle
     *
     * @return
     */
    @GetMapping("sendDeadLettle")
    public Result sendDeadLettle() {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 发送消息 已经在配置类设置了一个过期时间 10秒钟
        rabbitTemplate.convertAndSend(
                DeadLetterMqConfig.exchange_dead,
                DeadLetterMqConfig.routing_dead_1,
                "ok");

        System.out.println("发送消息的时间 ===>>> " + sdf.format(new Date()));

        return Result.ok();
    }

    /**
     * 发送消息 - 基于延迟插件实现延迟消息
     * http://localhost:8282/mq/sendDelay
     * @return
     */
    @GetMapping("sendDelay")
    public Result sendDelay() {
        // 设置时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 发送消息 - 自定义一个过期时间
        rabbitTemplate.convertAndSend(
                DelayedMqConfig.exchange_delay,
                DelayedMqConfig.routing_delay,
                "Ok",
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {

                        message.getMessageProperties().setDelay(10 * 1000);

                        System.out.println("发送消息的时间 ===>>> " + sdf.format(new Date()));

                        return message;
                    }
                });
        return Result.ok();
    }
}
